# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging

from cve_ease.models import DBModel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import close_all_sessions

logger = logging.getLogger('cve-ease')


def activate_session(session, options):
    """active sql session"""
    DBModel.metadata.create_all(bind=session.get_engine())

    db = session.new_session()
    logger.debug(" * successfully connect to sql ")

    return db


def purge_db(session):
    """clean all data model and recreate"""
    DBModel.metadata.drop_all(bind=session.get_engine())
    DBModel.metadata.create_all(bind=session.get_engine())


class SQLSession(object):
    def __init__(self, opts=None, debug=False):
        assert opts, "opts argument must not be empty"
        self.db_type = opts.DB_TYPE
        self.db_file_path = opts.DB_FILE_PATH
        self.db_user = opts.DB_USER
        self.db_password = opts.DB_PASSWORD
        self.db_host = opts.DB_HOST
        self.db_port = opts.DB_PORT
        self.opts = opts
        self.logger = logging.getLogger('cve-ease')

        if self.db_type == 'mysql':
            SQLALCHEMY_DATABASE_URL = "mysql+pymysql://{}:{}@{}:{}/{}".format(
                self.db_user,
                self.db_password,
                self.db_host,
                self.db_port,
                self.db_database
            )
            self.engine = create_engine(
                SQLALCHEMY_DATABASE_URL
            )
        elif self.db_type == 'postgresql':
            SQLALCHEMY_DATABASE_URL = "postgresql://{}:{}@{}:{}/{}".format(
                self.db_user,
                self.db_password,
                self.db_host,
                self.db_port,
                self.db_database
            )
            self.engine = create_engine(
                SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
            )
        else:
            SQLALCHEMY_DATABASE_URL = "sqlite:///{}".format(
                self.db_file_path
            )
            self.engine = create_engine(
                SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False},
                echo=debug
            )

    def get_engine(self):
        return self.engine

    def new_session(self):
        self.session = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
        return self.session()

    def recreate_db(self):
        DBModel.metadata.drop_all(self.engine)
        DBModel.metadata.create_all(self.engine)

    def close(self):
        # Deprecated since version 1.3: The Session.close_all() method is deprecated
        # and will be removed in a future release. Please refer to close_all_sessions().
        # self.session.close_all()
        close_all_sessions()
